package com.sbr.tbd.pages.administration.application;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sbr.fmw.pages.AbstractPage;
import com.sbr.tbd.model.Application;

public class ListApplicationsPage extends AbstractPage {

	private static final Logger LOG = LoggerFactory.getLogger(ListApplicationsPage.class);

	@FindBy(name="name")
	private WebElement name;
	@FindBy(name="description")
	private WebElement description;
	@FindBy(id="createApplicationSubmit")
	private WebElement submit;

	public ListApplicationsPage(WebDriver driver) {
		super(driver);
	}

	public ListApplicationsPage createApplication(Application application) {
		name.sendKeys(application.getName());
		description.sendKeys(application.getDescription());
		submit.click();
		return new ListApplicationsPage(driver);
	}

	public void clickOnSubmit() {
		submit.click();
	}
	
	public int getApplicationsListSize() {
		List<WebElement> applicationsList = driver.findElements(By.xpath("//div[@id='applicationsList']/tr"));
		LOG.info("nombre d'applications dans la liste : {}",applicationsList.size());
		return applicationsList.size();
	}

	public List<String> getErrors() {
		List<WebElement> errors = new ArrayList<WebElement>();;
		try {
			WebElement errorsList = driver.findElement(By.className("feedbackPanel"));
			errors = errorsList.findElements(By.tagName("li"));
		} catch(NoSuchElementException e) {
			LOG.info("aucune erreur de validation");
		}
		List<String> errorsStringList = new ArrayList<String>();
		for (WebElement error : errors) {
			LOG.info("erreur de validation : {}",error.getText());
			errorsStringList.add(error.getText());
		}

		return errorsStringList;
	}

}
